package com.sita.cfmoto.login;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.sita.cfmoto.ErrorCode;
import com.sita.cfmoto.R;
import com.sita.cfmoto.persistence.User;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.Account;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.UserLoginRequest;
import com.sita.cfmoto.rest.model.response.AccountResponse;
import com.sita.cfmoto.rest.model.response.Reply;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.activity.MainActivity;
import com.sita.cfmoto.utils.JsonUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.sita.cfmoto.utils.Connectivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Class LoginActivity is for
 *
 * @author xiaodong on 15/3/2.
 */
public class LoginActivity extends AppCompatActivity {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private static Boolean isQuit = false;
    @Bind(R.id.mobile)
    EditText mMobile;
    @Bind(R.id.password)
    EditText mPassword;
    private Toast toast;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isQuit = false;
        }
    };

    public static Intent newIntent() {
        return new Intent(GlobalContext.getGlobalContext(), LoginActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        toast = Toast.makeText(this, R.string.again_to_exit_app, Toast.LENGTH_SHORT);
    }

    @Override
    protected void onResume() {
        mMobile.forceLayout();
        super.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        if (toast != null) {
            toast.cancel();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick(R.id.btn_login)
    void clickLogin() {
        String mobile = mMobile.getText().toString();
        String password = mPassword.getText().toString();
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11 || !mobile.startsWith("1")) {
            mMobile.setError(getText(R.string.error_invalid_mobile));
            return;
        }
        if (mobile.length() > 11) {
            mobile = mobile.substring(0, 11);
            mMobile.setText(mobile);
        }
        if (TextUtils.isEmpty(password)) {
            mPassword.setError(getText(R.string.error_invalid_password));
            return;
        }

        if (!Connectivity.isConnected(this)) {
            ToastUtils.show(this, getText(R.string.must_enable_connectivity));
            return;
        }

        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .backgroundColor(getResources().getColor(R.color.white))
                .content(R.string.logining)
                .contentColor(getResources().getColor(R.color.black))
                .progress(true, 15000)
                .build();
        dialog.show();

        UserLoginRequest req = new UserLoginRequest();
        req.mobile = mobile;
        req.password = password;

        RestClient.getRestService().userLogin(req, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200) {
                    if (restResponse.mErrorCode.equals("0") && restResponse.mData != null) {
                        Gson gson = JsonUtils.getGson();
                        String s = gson.toJson(restResponse.mData);
                        AccountResponse accountResponse = gson.fromJson(s, AccountResponse.class);
                        Account account = accountResponse.account;
                        User user = new User();
                        user.setAccountId(Long.valueOf(account.getAccountId()));
                        user.setEmail(account.getEmail());
                        user.setMobile(account.getMobile());
                        user.setAddress(account.getAddress());
                        user.setAvatar(account.getAvatar());
                        user.setBirthday(account.getBirthday());
                        user.setGender(account.getGender());
                        user.setNickName(account.getNickName());
                        user.setSignature(account.getSignature());
                        user.setUniqueId(account.getUniqueId());
                        user.setUserName(account.getUserName());
                        user.setXmppUser(account.getAccountId());
                        user.setXmppPass(req.password);

                        if (account != null) {
                            PersistUtils.saveUser(user);
                            loginSuccess(dialog);
                        } else {
                            loginFailed(dialog);
                        }

                    } else {
                        loginFailed(dialog);
                    }
                } else {
                    loginFailed(dialog);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Reply reply = (Reply) error.getBodyAs(Reply.class);
                if (dialog != null && !dialog.isCancelled()) {
                    dialog.dismiss();
                }
                if (reply != null) {
                    if (reply.errorCode.equals(ErrorCode.MOBILE_NOT_EXIST)) {
                        Toast.makeText(LoginActivity.this, getString(R.string.not_found_mobile), Toast.LENGTH_LONG).show();
                    } else if (reply.errorCode.equals(ErrorCode.WRONG_PASSWORD)) {
                        Toast.makeText(LoginActivity.this, getString(R.string.wrong_password), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(LoginActivity.this, getString(R.string.register_failed), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    private void loginFailed(MaterialDialog dialog) {
        Toast.makeText(LoginActivity.this, "登录失败, 请重试！", Toast.LENGTH_LONG).show();
        dialog.dismiss();
    }

    private void loginSuccess(MaterialDialog dialog) {
        if (dialog != null && !dialog.isCancelled()) {
            dialog.dismiss();
        }
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        LoginActivity.this.finish();

//        VehicleUtils.fetchBindedVehicles(new VehicleUtils.FetchBindedVehiclesCallback() {
//            @Override
//            public void onBindedVehiclesFetched(List<BindedVehicle> vehicles) {
//                if (vehicles == null || vehicles.isEmpty()){
//                    // no binding
//                    // 如果已经注册成功，但是未绑定成功，或者没有状态，直接跳进绑定页面
////                    startActivity(BindingActivity.newIntent());
//                    Intent intent = new Intent();
//                    intent.setClass(LoginActivity.this, BindVehicleActivity.class);
//                    intent.putExtra("isToMain",true);
//                    startActivity(intent);
//                } else {
//                    if (vehicles != null && !vehicles.isEmpty() && vehicles.size() >= 1){
//                        BindedVehicle vehicle = vehicles.get(0);
////                        LocalStorage.setCurrSelectedVehicle(vehicle.vinId);
//                        VehicleUtils.setCurrentSelectedVehicle(vehicle.vin);
//                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                    } else {
//                        // 如果已经注册成功，但是激活成功，直接跳进激活页面
////                        startActivity(new Intent(LoginActivity.this, ActivationActivity.class));
//                    }
//                }
////                startActivity(new Intent(LoginActivity.this, MainActivity.class));
//
//            }
//        });
    }

    @OnClick(R.id.btn_register)
    void clickRegister() {
        startActivity(RegisterActivity.newIntent());
        finish();
//        overridePendingTransition(0, 0);
    }

    @OnClick(R.id.btn_forget_password)
    void clickForgetPassword() {
        startActivity(ForgetActivity.newIntent(this));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isQuit) {
                isQuit = true;
//                Toast.makeText(LoginActivity.this, R.string.again_to_exit_app,
//                        Toast.LENGTH_SHORT).show();
                toast.show();
                // 利用handler延迟发送更改状态信息
                mHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                finish();
//                exitAppComplete();
            }
        }
        return false;
    }

    protected void exitAppComplete() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            this.finishAffinity();
            System.exit(0);
        } else {
            this.finish();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
}

